package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.dtos.WmUpOrDownDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper,WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1  参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2  查询参数封装
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
        //  标题模糊查找
        if (dto.getKeyword() != null) {
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //  频道查找
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //  文章状态
        if (dto.getStatus()!=null) {
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //  开始时间 结束时间
        // 发布时间 >= 开始时间
        wrapper.ge(dto.getBeginPubDate() != null,WmNews::getPublishTime, dto.getBeginPubDate());
        // 发布时间 <= 开始时间
        wrapper.le(dto.getEndPubDate()!=null,WmNews::getPublishTime, dto.getBeginPubDate());
        //  根据用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId,user.getId());
        //  时间降序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //  定义分页
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //  执行查询
        IPage<WmNews> pageResult = page(page, wrapper);
        //  封装要返回的结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());

        result.setData(pageResult.getRecords());
        // 处理文章图片
        result.setHost(webSite);
        return result;
    }
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Transactional
    @Override
    public ResponseResult submit(WmNewsDTO dto) {
        //  参数检查
        if (StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"参数检测错误");
        }
        //   登录检查
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //  属性拷贝
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        String images = imageListToStr(dto.getImages(), webSite);
        wmNews.setImages(images);
        saveWmNews(wmNews);
        // TODO 3.1 抽取文章中关联的图片路径
        //  dto中的Content数据为，前前端传到后端的文章（图片）数据,格式为JSON
        //  将JSON数据转为对象，下面将其以map的格式存入数组
        List<Map> contents = JSON.parseArray(dto.getContent(), Map.class);
        //  对上面的数组筛选，得到 图片的数组集合
        List<String> materials=parseContentImages(contents);

        // TODO 3.2 关联文章内容中的图片和素材关系
        //  检测类型 是草稿还是发表  草稿不用进行关联
        Short status = dto.getStatus();


        if (status == WmNews.Status.SUBMIT.getCode()) {
            saveRelativeInfoForCover(dto,materials, wmNews);
        }

        //  发送待审核消息文章的id 到Mq中
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("文章的Id{}，成功发动到mq中",wmNews.getId());

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getOneById(Integer id) {
        //1 参数检查
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2  查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult deleteOneById(Integer id) {
        //1 参数检查
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2  执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
           throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult news_down_or_up(WmNewsDTO dto) {
        // 1 参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable) && !WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    WmNewsMapper wmNewsMapper;
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        // 1.  参数检测
        dto.checkParam();
        //  2.  记录当前页
        Integer currentPage = dto.getPage();
        //    设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        //   2  分页查询
        List<WmNewsVO> wmNewsVOList = wmNewsMapper.findListAndPage(dto);
        //统计个数
        long count = wmNewsMapper.findListCount(dto);
        //  封装返回结果
        PageResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVOList);
        result.setHost(webSite);

        return result;

    }
    @Autowired
    WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }
    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1   参数检查
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2    查询文章
        WmNews wmNews = this.getById(dto.getId());

        //   检测文章状态   状态为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }

        //3  修改文章
        wmNews.setStatus((short)status);
        updateById(wmNews);
        //5. 通知定时发布文章
        if (status.equals((short)4)) {
            // 发布时间
            long publishTime = wmNews.getPublishTime().getTime();
            // 当前时间
            long nowTime = System.currentTimeMillis();
            //延时时间
            long delayTime = publishTime-nowTime<=0?0:publishTime-nowTime;
            // 发布文章
            rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                    , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                    , wmNews.getId()
                    , new MessagePostProcessor() {
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            message.getMessageProperties().setHeader("x-delay",delayTime);
                            return message;
                        }
                    });

            log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());

        }
        return ResponseResult.okResult();
    }

    /**
     *      文章上架下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult upOrDown(WmUpOrDownDTO dto) {
        //1.检查参数
        if (StringUtils.isBlank(dto.getEnable())||StringUtils.isBlank(dto.getId())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.查询文章
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.判断文章是否发布
        //  发布状态   请求的enable 为  0    为下架操作
        if (wmNews.getStatus() != (short)9 ){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章没有上架，不允许操作");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        if (wmNews.getArticleId()!=null) {
            if (dto.getEnable().equals("0")) {
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE
                        ,NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY
                        ,wmNews.getArticleId()
                );
            }
            //  上架
            if (dto.getEnable().equals("1")) {
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE
                        ,NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY
                        ,wmNews.getArticleId()
                );

            }

        }

        //5. 上下架发送消息通知
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));
        //  下架



        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }


    /**
     * 【3.3】 关联文章封面中的图片和素材关系
     * @param dto  前端用户选择封面信息数据
     * @param materials  从内容中解析的图片列表
     * @param wmNews     文章ID
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materials, WmNews wmNews) {
        // 前端用户选择的图
        List<String> images = dto.getImages();

        // 自动获取封面 ****
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int materialSize = materials.size();
            if (materialSize > 0 && materialSize <= 2) {  // 单图
                images =  materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (materialSize > 2) { // 多图
                images =  materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {  // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            if (images != null && images.size() > 0) {
                // 将图片集合 转为字符串  url1,url2,url3
                wmNews.setImages(imageListToStr(images,webSite));
            }
            updateById(wmNews);
        }
        // 保存图片列表和素材的关系
        if (images != null && images.size() > 0) {
            images = images.stream().map(x->x.replace(webSite,"")
                    .replace(" ","")).collect(Collectors.toList());
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }





    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或修改文章
     * @param wmNews 文章对象（前端传递）
     */
    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP); // 上架
        if (wmNews.getId()==null) { // 保存操作
            save(wmNews);
        }else {  // 修改
            // 当前文章 和 素材关系表数据删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    /**
     *
     * @param urls   图片列表
     * @param newsId  文章id
     * @param type    类型 0：内容素材  1：封面素材
     */
    private void saveRelativeInfo(List<String> urls, Integer newsId, Short type) {
        //  查询图片对应 的id
        List<Integer> integersIds = wmNewsMaterialMapper.selectRelationsIds(urls, WmThreadLocalUtils.getUser().getId());
        //  判断 素材是否缺失
        if (CollectionUtils.isEmpty(integersIds) || integersIds.size() < urls.size()) {//素材id列表没有数据
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //  保存关系
        wmNewsMaterialMapper.saveRelations(integersIds,newsId,type);
    }

    private List<String> parseContentImages(List<Map> contents) {
        List<String> imagesList = contents.stream()
                //  过滤  只要 类型为图片的
                .filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                //  获取  image 下的value  图片的URL
                .map(x -> (String) x.get("value"))
                //  去除前缀
                .map(url -> url.replace(webSite, "").replace(" ", ""))
                //  去重
                .distinct()
                //  stram 转为  list
                .collect(Collectors.toList());
        return imagesList;
    }

    /**
     *      图片集合转字符串
     * @param images
     * @param webSite
     * @return
     */
    private String imageListToStr(List<String> images, String webSite) {
        return images.stream()
                .map((url)-> url.replace(webSite,""))
                .collect(Collectors.joining(","));

    }



}
